package com.hadoop.controller;

import com.google.gson.Gson;
import com.hadoop.common.Constants;
import com.hadoop.component.UploadFileBizComponent;
import com.hadoop.dao.redis.RedisDao;
import com.hadoop.mybatis.po.User;
import com.hadoop.mybatis.vo.FileAttrVo;
import com.hadoop.util.HadoopConnectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * <p>文件上传通用类</p>
 *
 * @author Andy
 * @date 2017/10/13
 */
@Controller
@RequestMapping(value = "/hadoop")
public class UploadController {

    @Resource
    private UploadFileBizComponent uploadFileBizComponent;

    @Resource
    private RedisDao redisDao;

    @RequestMapping(value = "/goto/upload/page")
    public String gotoUplaodPage() {
        return "/storage/upload";
    }

    @RequestMapping(value = "/upload/file")
    public String upload(@RequestParam MultipartFile file, HttpServletRequest request, Model model) throws IOException {
        if (null == file || file.getSize() == 0) {
            model.addAttribute("msg", "请先选择需要上传的文件");
            return "redirect:/hadoop/goto/upload/page";
        }

        User user = (User) request.getSession().getAttribute("user");

        String fileName = file.getOriginalFilename();
        long fileSize = file.getSize();
        String dateFormat = DateTime.now().toString("yyyy-MM-dd HH:mm:ss");
        FileAttrVo fileAttrVo = new FileAttrVo(fileName, fileSize, dateFormat);

        String destPath = request.getServletContext().getRealPath("/content");

        File dest = new File(destPath, fileName);
        file.transferTo(dest);

        //写进HDFS中
        FileSystem hdfs = HadoopConnectionUtils.getFileSystem();
        Path srcPath = new Path(dest.getAbsolutePath());
        Path destHdfsPath = new Path("/data/");
        hdfs.copyFromLocalFile(srcPath,destHdfsPath);
        hdfs.close();

        fileAttrVo.setFile(dest);
        String key = Constants.UPLOAD_FILE_USERNAME + user.getUserName();
        String msg = "上传成功";
        if (!uploadFileBizComponent.uploadFile(key, fileAttrVo)) {
            msg = "上传失败";
        }

        //删除本地的上传文件
        dest.delete();
        model.addAttribute("msg", msg);

        return "redirect:/hadoop/file/list";
    }

    @RequestMapping(value = "/download")
    public void download(HttpServletRequest request, HttpServletResponse response, String fileName) throws IOException {
        /*User user = (User) request.getSession().getAttribute("user");
        String key = Constants.UPLOAD_FILE_USERNAME + user.getUserName();
        String json = redisDao.hget(key, fileName);
        Gson gson = new Gson();
        FileAttrVo fileAttrVo = gson.fromJson(json, FileAttrVo.class);*/

        //从hdfs中下载
        String destPath = request.getServletContext().getRealPath("/content");
        FileSystem hdfs = HadoopConnectionUtils.getFileSystem();
        Path srcPath = new Path("/data/"+fileName);
        Path destHdfsPath = new Path(destPath);
        System.out.println("hdfs cpToLocal src:" + srcPath.getName());
        System.out.println("hdfs cpToLocal dst:" + destPath);
        hdfs.copyToLocalFile(false, srcPath, destHdfsPath, true);
        File file = new File(destPath, fileName);
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        try {
            response.setContentType("application/octet-stream");
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {   //IE浏览器
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = URLDecoder.decode(fileName, "UTF-8");//其他浏览器
            }

            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1")); // 指定下载的文件名
            os.write(FileUtils.readFileToByteArray(file));
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }
}
